package com.zha;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class Zouye2_2 {
    public static Connection conn = null;
    public static TableName tName = TableName.valueOf("t_student_course");
    public static TableName tStudent = TableName.valueOf("t_student");
    public static TableName tCourse = TableName.valueOf("t_course");
    public static Random ra = new Random();

    @Before
    public void init() throws IOException {
        //配置//构建一个连接对象
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "hbase:2181,hbase-01:2181,hbase-02:2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    /**
     * 创建学生课程表
     * @throws IOException
     */
    @Test
    public void create() throws IOException{
        //从连接中构造一个DDL操作器
        Admin admin = conn.getAdmin();
        if(admin.tableExists(tName)){
            admin.disableTable(tName);
            admin.deleteTable(tName);
        }
        //创建表定义描述对象
        HTableDescriptor ht = new HTableDescriptor(tName);
        //创建列族定义描述对象
        HColumnDescriptor hc = new HColumnDescriptor("cf1".getBytes());
        //设置该列族中存储数据的最大版本数，默认是1
        hc.setMaxVersions(5);
        hc.setBlockCacheEnabled(true);
        hc.setBlocksize(180000);
        //将列族定义信息对象放入表定义对象中
        ht.addFamily(hc);
        //用DDL操作器对象：admin来建表
        admin.createTable(ht);
        System.out.println("表创建完成");
    }


    /**
     * 学生课程表插入数据
     * @throws IOException
     */
    @Test
    public void insert() throws IOException{
        Table table = conn.getTable(tName);
        List<Put> putList = new ArrayList<Put>();
        //学生1 student2016030421164483174
        String stu1 = "student2016030421164483174";
        //学生2  student2016030421164417190
        String stu2 = "student2016030421164417190";
        //学生3  student2016030421164462988
        String stu3 = "student2016030421164462988";
        ////课程1 2 3 course2016030421165195800   course201603042116517244   course2016030421165117240
        Put put1 = new Put("student2016030421164483174_course2016030421165195800".getBytes());
        put1.addColumn("cf1".getBytes(),"studnet".getBytes(),stu1.getBytes());

        Put put2 = new Put("student2016030421164483174_course201603042116517244".getBytes());
        put2.addColumn("cf1".getBytes(),"studnet".getBytes(),stu1.getBytes());

        Put put3 = new Put("student2016030421164483174_course2016030421165117240".getBytes());
        put3.addColumn("cf1".getBytes(), "student".getBytes(), stu1.getBytes());

        Put put4 = new Put("student2016030421164417190_course2016030421165195800".getBytes());
        put4.addColumn("cf1".getBytes(), "student".getBytes(), stu2.getBytes());

        Put put5 = new Put("student2016030421164417190_course201603042116517244".getBytes());
        put5.addColumn("cf1".getBytes(), "student".getBytes(), stu2.getBytes());

        Put put6 = new Put("student2016030421164462988_course2016030421165195800".getBytes());
        put6.addColumn("cf1".getBytes(), "student".getBytes(), stu3.getBytes());
        putList.add(put1);
        putList.add(put2);
        putList.add(put3);
        putList.add(put4);
        putList.add(put5);
        putList.add(put6);
        table.put(putList);
        System.out.println("数据插入完成");
    }

    /**
     * 查询某个学生所选的所有课程列表 学生1
     */
    @Test
    public void findCourseByStudent() throws IOException{
        Table table = conn.getTable(tName);
        String stuId = "student2016030421164483174";
        ArrayList<String> courseIds = new ArrayList<String>();
        //创建全表扫描的scan
        Scan scan = new Scan();
        //过滤以stuId_开头的
        RowFilter rf1 = new RowFilter(CompareFilter.CompareOp.EQUAL,new RegexStringComparator(stuId+"_"));
        scan.setFilter(rf1);
        //把扫描结果放在rs1中
        ResultScanner rs1 = table.getScanner(scan);
        //从rs1中迭代遍历出结果it
        Iterator<Result> it = rs1.iterator();
        //判断it有没有了
        while(it.hasNext()){
            Result result = it.next();
            //把结果转化为byte类型
            byte[] rowKey = result.getRow();
            //添加到list的course中
            courseIds.add(new String(rowKey,"utf8"));
        }
        //从list中去数据
        for(String id : courseIds){
            String courseId = id.split("_")[1];
            //创建了连接
            Table  courseTable = conn.getTable(tCourse);

            Get get = new Get(courseId.getBytes());
            Result result= courseTable.get(get);
            byte[] name = result.getValue("cf1".getBytes(), "name".getBytes());
            System.out.println("学生ID:"+stuId+" 名称："+ new String("课程ID"+courseId));
        }
    }

    /**
     * 查询某个课程，的学生列表课程1
     * @throws IOException
     */

    @Test
    public void findStudentByCourse() throws IOException{
        Table table = conn.getTable(tName);
        //course学生列表课程1
        String courseId = "course2016030421165195800";
        List<String> studentIds = new ArrayList<String>();
        Scan scan = new Scan();
        RowFilter rf1 = new RowFilter(CompareFilter.CompareOp.EQUAL, new RegexStringComparator("_"+courseId));//过滤的方法
        scan.setFilter(rf1);     //全盘扫描过滤（用上面的方法）
        ResultScanner rs1 = table.getScanner(scan);
        Iterator<Result> it = rs1.iterator();
        while(it.hasNext()){
            Result result = it.next();
            byte[] rowKey = result.getRow();
            studentIds.add(new String(rowKey,"utf8"));
        }
        for(String id : studentIds){
            String stuId = id.split("_")[0];   //[0]切下来去前面的
            Table  stuTable = conn.getTable(tStudent);
            Get get = new Get(stuId.getBytes());
            Result result= stuTable.get(get);
            //cf1 列族       name 为列里面的key   最后得到byte的二进制数组
            byte[] name = result.getValue("cf1".getBytes(), "name".getBytes());
            System.out.println("学生ID"+ courseId + "  名字"+ new String("课程ID"+stuId));
////            String studendsname = new String(name,"utf-8");
//            System.out.println(studendsname);
        }
    }

    /**
     * 学生可以修改所选的课程  将学生1的课程1去掉
     * @throws IOException
     */

//    @Test
//    public void changeCourseOfStudent() throws IOException{
//        String stuId ="student2016030421164483174";
//        String courseId ="course2016030421165195800";
//        String scId = stuId+"_" + courseId;
//        Delete delete = new Delete(scId.getBytes());              //创建一个对象
//        Table table = conn.getTable(tName);
//        table.delete(delete);                                     //表 删除 删除内容
//    }
//
//    @After
//    public void after() throws IOException {
//        if(conn!=null){
//            conn.close();
//        }
//    }

    /**
     * 删除表
     */

//    @Test
//    public void testDropTable() throws IOException {
//        Admin admin = conn.getAdmin();
//        //停用表
//        admin.disableTable(TableName.valueOf("t_student"));
//        //删除表
//        admin.deleteTable(TableName.valueOf("t_student"));
//
//        admin.close();
//        conn.close();
//    }
}

